package com.imooc.common.thread;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by deng_wb on 2019/8/17
 */
public class ThreadTest {

    int count = 0;
    synchronized void m() {
        for (int i = 0; i < 10000; i++) count++; // 为什么多线程中i++不是线程安全的，首先++操作不是原子的，要经过读取计算和写回
    }

    @Test
    public void run1() {
        ThreadTest test = new ThreadTest();
        List<Thread> threads = new ArrayList<Thread>();

        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(test::m, "thread-" + i));
        }

        threads.forEach((o) -> o.start());
        threads.forEach((o) -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(test.count);
    }

}
